package org.zhaya.sdk.processors.condition;

import io.logz.sawmill.Condition;
import io.logz.sawmill.Doc;
import io.logz.sawmill.annotations.ConditionProvider;
import io.logz.sawmill.parser.ConditionParser;
import io.logz.sawmill.utilities.JsonUtils;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

@ConditionProvider(type = "exists", factory = FieldExistsCondition.Factory.class)
public class FieldExistsCondition implements Condition {
    private final String field;

    public FieldExistsCondition(String field) {
        this.field = field;
    }

    @Override
    public boolean evaluate(Doc doc) {
        boolean flag = doc.hasField(this.field);
        if (flag) {
            Object value = doc.getField(this.field);
            if (value == null) {
                return false;
            }
            if (value instanceof List) {
                return CollectionUtils.size(value) != 0;
            }
            if (value instanceof String) {
                return StringUtils.isNotBlank((String) value);
            }
        }
        return flag;
    }

    public static class Factory implements Condition.Factory {

        @Override
        public Condition create(Map<String, Object> config, ConditionParser conditionParser) {
            Configuration existsCondition = JsonUtils.fromJsonMap(Configuration.class, config);

            return new FieldExistsCondition(existsCondition.getField());
        }
    }

    @Data
    public static class Configuration {
        private String field;

    }
}